package life.huangzhi.community.community.controller;

import life.huangzhi.community.community.mapper.QuestionMapper;
import life.huangzhi.community.community.model.Question;
import life.huangzhi.community.community.model.User;
import life.huangzhi.community.community.service.QuestionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 * @date 2019/12/1 17:04
 */
@Controller
@RequestMapping("/publish")
public class PublishController {

    @Resource
    private QuestionService queryService;
    @Resource
    private QuestionMapper questionMapper;

    /**
     * 进入编辑问题界面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable(name = "id") Integer id, HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("user");
        Question question = questionMapper.getById(id);
        if (question == null) {
            model.addAttribute("msg", "没有这条数据");

        } else {
            if (user.getId().equals(question.getCreator())) {
                model.addAttribute(question);
                model.addAttribute("title", "修改");
                model.addAttribute("msg", "您没有权限");
                return "publish";
            }
        }
        return "error";
    }

    /**
     * 进入新增问题界面
     */
    @GetMapping("turnTo/")
    public String publish() {
        return "publish";
    }

    /**
     * 新增或更新
     */
    @PostMapping("/save")
    public String doPublish(Question question, HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            model.addAttribute("error", "用户未登录");
            return "publish";
        }
        String msg = queryService.createOrUpdate(question, user);
        model.addAttribute("msg" , msg);
        return "redirect:/";
    }
}
